import {AfterViewInit, Component, OnInit, ViewChild} from '@angular/core';
import {OneOperationComponent} from "../../../widgets/one-operation/one-operation.component";
import {ActivatedRoute, Router} from "@angular/router";
import {PageSubject} from "../../../util/page-subject";
import {DataDictionaryService} from "../../../services/dataDictionary.service";
import {TableUtil} from "../../../util/table-util";
import {DataSourceService} from "./data-source.service";
import {OneDialogService} from "../../../widgets/one-dialog/one-dialog.service";
import {ResponseUtil} from "../../../util/response-util";
import {Path} from "../../../portal/admin/admin-breadcrumb/breadcrumb";
import {MsgResult} from "../../../models/msg-result";
import {MsgConstants} from "../../../constants/constants";
import {TemplateAPI} from "../template-constants";

declare var $;

@Component({
  selector: 'app-data-source',
  templateUrl: './data-source.component.html',
  styleUrls: ['./data-source.component.css']
})
export class DataSourceComponent implements OnInit, AfterViewInit {


  @ViewChild(OneOperationComponent) operation: OneOperationComponent;
  //存储初始化表单数据

  id: Array<string> = [];

  table;

  dictionary;

  constructor(private route: Router,
              private router: ActivatedRoute,
              private pageSubject: PageSubject,
              private dataSourceService: DataSourceService,
              private dataDictionarysService: DataDictionaryService,
              private tableUtil: TableUtil,
              private dialogService: OneDialogService,
              private response: ResponseUtil) {
  }

  proxy = {
    "dataSourceAdd": () => this.dataSourceAdd(),
    "dataSourceUpdate": () => this.dataSourceUpdate(),
    "dataSourceDelete": () => this.dataSourceDelete()
  };

  ngOnInit() {
    this.pushPage();
    this.initIsYesOrNo();
  }

  ngAfterViewInit() {
    //操作函数代理
    this.operation.proxy = this.proxy;
  }

  /**
   * 面包屑导航
   */
  pushPage() {
    let path = new Path("模板引擎", "");
    this.pageSubject.pushPage("数据源管理", "查询", path);
  }

  /**
   * 添加页面跳转
   */
  dataSourceAdd() {
    this.route.navigate(['add'], {relativeTo: this.router});
  }

  /**
   * 实现删除弹窗
   */
  dataSourceDelete() {
    let rows = this.table.bootstrapTable('getSelections');
    this.id = this.tableUtil.getCloumns(rows, "id");
    if (undefined == this.id || 0 == this.id.length) {
      this.dialogService.modalInfo("请选择一条数据");
    } else {
      this.dialogService.modalInfoWithCancelBtn("确定删除？", this.requestDelete);
    }

  }

  /**
   * 实现删除操作
   * 1.调取后端删除操作；
   */
  private requestDelete = () => {
    //调用后端接口
    if (this.id.length == 1) {
      this.dataSourceService.deleteDataSource(this.id[0]).subscribe(
        result => this.response.success(result, this.processDeleteResult),
        message => this.response.error(message)
      );
    } else {
      this.dataSourceService.deleteDataSources(this.id).subscribe(
        result => this.response.success(result, this.processDeleteResult),
        message => this.response.error(message)
      );
    }
  }
  private processDeleteResult = (result: MsgResult) => {
    if (result && result.code == MsgConstants.MSG_CODE_OK) {
      this.dialogService.success(result.message);
      this.search();
    }
    if (result && result.code != MsgConstants.MSG_CODE_OK) {
      this.dialogService.info(result.message);
    }
  }

  search() {
    this.table.bootstrapTable('refresh');
  }

  /**
   * 修改页面跳转传参
   */
  dataSourceUpdate() {
    let rows = this.table.bootstrapTable('getSelections');
    this.id = this.tableUtil.getCloumns(rows, "id");
    if (this.id.length != 1) {
      this.dialogService.modalInfo("请选择一条数据");
    } else {
      this.route.navigate(['update', {id: this.id[0]}], {relativeTo: this.router});
    }
  }

  /**
   * 查询
   */
  loadDataSources() {
    this.table = this.tableUtil.load("one_table_dataSource", {
      columns: [
        {checkbox: true},
        {field: "id", title: 'ID', align: 'left', visible: false, switchable: false},
        {field: "code", title: '数据源编码', align: 'left', switchable: false},
        {field: "name", title: '数据源名称', align: 'left', switchable: false},
        {field: "type", title: '类型', align: 'left'},
        {field: "dataFromSrc", title: '来源', align: 'left'},
        {field: "orderBy", title: '排序', align: 'left'},
        {field: "url", title: '数据源URL', align: 'left', formatter: this.tableUtil.showToolTip},
        {field: "isUse", title: '有效', align: 'left', formatter: this.yesOrNoFormat},
        {field: "creatorName", title: '创建人', align: 'left'},
        {field: "create_date", title: '创建日期', align: 'left', sortName: "CREATE_DATE", sortable: true},
        {field: "updatorName", title: '修改人', align: 'left', visible: false},
        {field: "update_date", title: '修改日期', align: 'left', sortName: "UPDATE_DATE", sortable: true, visible: false}
      ],
      idField: "id",
      sidePagination: 'server',
      pagination: true,
      pageNumber: 1,
      pageSize: 15,
      pageList: [10, 15, 50],
      paginationPreText: "上一页",
      paginationNextText: "下一页",
      paginationLoop: false,//是否开启循环分页
      singleSelect: false,//多选
      clickToSelect: true,//点击选中
      toolbar: "#one_operation_data-source",
      url: TemplateAPI.dataSourcesPageListV2,
      method: 'post',
      //传递附加参数
      queryParams: (params) => {
        params.dataSourceName = $("#dataSourceName").val();
        return params;
      },
      //返回数据处理器
      responseHandler: (result) => {
        return this.response.bsPageHandler(result, (result) => {
          console.log(result);
          result.data.rows.forEach(function (value) {
            value.create_date = value.createDate || '';
            value.update_date = value.updateDate || '';
          });
        });
      },
      height: 700,//table高度
      sortable: true,
      sortOrder: 'desc',
      sortName: 'CREATE_DATE',
      showColumns: true,//显示自定义显示列按钮
      showRefresh: true,//显示刷新按钮
      minimumCountColumns: 3,//最少保留显示的列数量
      showToggle: true,//显示视图切换按钮
      showPaginationSwitch: true,//显示是否分页切换按钮
      classes: "table table-hover",
      striped: true,//隔行变色
      mobileResponsive: true//响应式
    });
  }

  /**
   * 获取所有的数据源类型
   */
  initIsYesOrNo() {
    this.dataDictionarysService.getChildDicByCode('QYZT').subscribe(
      result => this.response.success(result, this.processTypeResult),
      message => this.response.error(message)
    );
  }

  /**
   *  获取所有类型
   * @param json
   */
  private processTypeResult = (result: MsgResult) => {
    // console.log(result);
    if (result && result.code == MsgConstants.MSG_CODE_OK) {
      this.dictionary = result.data;
      this.loadDataSources();
    }
    if (result && result.code != MsgConstants.MSG_CODE_OK) {
      this.dialogService.info(result.message);
    }
  }

  /**
   * yesOrNo格式化函数
   * @param value
   * @param row
   * @param index
   * @returns {any}
   */
  private yesOrNoFormat = (value, row, index) => {
    console.log("value:" + value);
    const dicArr = this.dictionary.filter((val) => {
      return value == val.value
    });
    return dicArr[0].display;
  }
}
